


package ciicos.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ciicos.annotation.JnpfField;
import ciicos.base.ActionResult;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.base.UserInfo;
import ciicos.base.vo.DownloadVO;
import ciicos.config.ConfigValueUtil;
import ciicos.exception.DataException;
import ciicos.onlinedev.model.OnlineImport.ExcelImFieldModel;
import ciicos.onlinedev.model.OnlineImport.ExcelImportModel;
import ciicos.onlinedev.model.OnlineImport.VisualImportModel;
import ciicos.permission.entity.UserEntity;
import org.springframework.transaction.annotation.Transactional;
import ciicos.base.entity.ProvinceEntity;
import ciicos.model.linequestion.*;
import ciicos.model.linequestion.LineQuestionPagination;
import ciicos.entity.*;
import ciicos.entity.LineQuestionOptionsEntity;
import ciicos.util.*;
import ciicos.base.util.*;
import ciicos.base.vo.ListVO;
import ciicos.util.context.SpringContext;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.Cleanup;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ciicos.entity.LineQuestionEntity;
import ciicos.service.LineQuestionService;
import ciicos.entity.LineQuestionOptionsEntity;
import ciicos.service.LineQuestionOptionsService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import ciicos.util.GeneraterSwapUtil;

import java.util.stream.Collectors;
import java.util.*;

import cn.xuyanwu.spring.file.storage.FileInfo;


/**
 * 题库管理
 *
 * @版本： V3.2.0
 * @版权：
 * @作者： 企业研发中心
 * @日期： 2025-10-07
 */
@Slf4j
@RestController
@Api(tags = "题库管理", value = "line")
@RequestMapping("/api/line/LineQuestion")
public class LineQuestionController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;


    @Autowired
    private UserProvider userProvider;


    @Autowired
    private LineQuestionService lineQuestionService;

    @Autowired
    private LineQuestionOptionsService lineQuestionOptionsService;


    /**
     * 列表
     *
     * @param lineQuestionPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody LineQuestionPagination lineQuestionPagination) throws IOException {
        //树形判断是否有参数，有参数不造树
        List<LineQuestionEntity> list = lineQuestionService.getList(lineQuestionPagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<LineQuestionListVO> listVO = JsonUtil.getJsonToList(list, LineQuestionListVO.class);
        for (LineQuestionListVO lineQuestionVO : listVO) {
            ActionResult info = info(lineQuestionVO.getId());
            Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
            lineQuestionVO.setType_name(generaterSwapUtil.getDicName(lineQuestionVO.getType(), "745222977217364869"));

            lineQuestionVO.setQuestiontype_name(lineQuestionVO.getQuestiontype());

            lineQuestionVO.setEnabledmark_name(generaterSwapUtil.switchSelectValue(lineQuestionVO.getEnabledmark(), "启用", "禁用"));

            lineQuestionVO.setQuestion_name(lineQuestionVO.getQuestion());

            lineQuestionVO.setAnswer_name(lineQuestionVO.getAnswer());

            lineQuestionVO.setCreatoruserid_name(generaterSwapUtil.userSelectValue(lineQuestionVO.getCreatoruserid()));

            lineQuestionVO.setCreatortime_name(lineQuestionVO.getCreatortime());

            lineQuestionVO.setLastmodifyuserid_name(generaterSwapUtil.userSelectValue(lineQuestionVO.getLastmodifyuserid()));

            lineQuestionVO.setLastmodifytime_name(lineQuestionVO.getLastmodifytime());

            //子表数据转换
            List<LineQuestionOptionsEntity> lineQuestionOptionsList = lineQuestionService.getLineQuestionOptionsList(lineQuestionVO.getId(), lineQuestionPagination);
            List<LineQuestionOptionsModel> lineQuestionOptionsModelList = JsonUtil.getJsonToList(lineQuestionOptionsList, LineQuestionOptionsModel.class);
            int lineQuestionOptionsNum = 0;
            for (LineQuestionOptionsModel lineQuestionOptionsModel : lineQuestionOptionsModelList) {
                lineQuestionOptionsModel.setIsanswer(generaterSwapUtil.switchSelectValue(lineQuestionOptionsModel.getIsanswer(), "是", "否"));
                lineQuestionOptionsNum++;
            }
            lineQuestionVO.setLineQuestionOptionsList(lineQuestionOptionsModelList);
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(lineQuestionPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param lineQuestionForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid LineQuestionForm lineQuestionForm) throws DataException {
        String b = lineQuestionService.checkForm(lineQuestionForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        lineQuestionForm.setCreatoruserid(userInfo.getUserId());
        lineQuestionForm.setCreatortime(DateUtil.getNow());
        LineQuestionEntity entity = JsonUtil.getJsonToBean(lineQuestionForm, LineQuestionEntity.class);
        entity.setId(mainId);
        lineQuestionService.save(entity);
        if (lineQuestionForm.getLinequestionoptionsList() != null) {
            List<LineQuestionOptionsEntity> LineQuestionOptionsList = JsonUtil.getJsonToList(lineQuestionForm.getLinequestionoptionsList(), LineQuestionOptionsEntity.class);
            for (LineQuestionOptionsEntity entitys : LineQuestionOptionsList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setQuestionid(entity.getId());

                lineQuestionOptionsService.save(entitys);
            }
        }


        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<LineQuestionInfoVO> info(@PathVariable("id") String id) {
        LineQuestionEntity entity = lineQuestionService.getInfo(id);
        LineQuestionInfoVO vo = JsonUtil.getJsonToBean(entity, LineQuestionInfoVO.class);
        vo.setCreatoruserid(generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));
        if (vo.getCreatortime() != null) {
            vo.setCreatortime(vo.getCreatortime());
        }
        vo.setLastmodifyuserid(generaterSwapUtil.userSelectValue(vo.getLastmodifyuserid()));
        if (vo.getLastmodifytime() != null) {
            vo.setLastmodifytime(vo.getLastmodifytime());
        }

        //子表
        List<LineQuestionOptionsEntity> LineQuestionOptionsList = lineQuestionService.getLineQuestionOptionsList(id);
        for (LineQuestionOptionsEntity linequestionoptionsEntity : LineQuestionOptionsList) {
        }
        vo.setLineQuestionOptionsList(JsonUtil.getJsonToList(LineQuestionOptionsList, LineQuestionOptionsModel.class));
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<LineQuestionInfoVO> detailInfo(@PathVariable("id") String id) {
        ActionResult info = info(id);
        Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
        LineQuestionEntity entity = lineQuestionService.getInfo(id);
        LineQuestionInfoVO vo = JsonUtil.getJsonToBean(entity, LineQuestionInfoVO.class);

        //子表数据转换
        List<LineQuestionOptionsEntity> lineQuestionOptionsList = lineQuestionService.getLineQuestionOptionsList(id);
        List<LineQuestionOptionsModel> lineQuestionOptionsModelList = JsonUtil.getJsonToList(lineQuestionOptionsList, LineQuestionOptionsModel.class);
        int lineQuestionOptionsNum = 0;
        for (LineQuestionOptionsModel lineQuestionOptionsModel : lineQuestionOptionsModelList) {
            lineQuestionOptionsModel.setIsanswer(generaterSwapUtil.switchSelectValue(lineQuestionOptionsModel.getIsanswer(), "是", "否"));
            lineQuestionOptionsNum++;
        }
        vo.setLineQuestionOptionsList(lineQuestionOptionsModelList);

        //附表数据转换

//添加到详情表单对象中
        vo.setType(generaterSwapUtil.getDicName(vo.getType(), "745222977217364869"));

        vo.setQuestiontype(vo.getQuestiontype());

        vo.setEnabledmark(generaterSwapUtil.switchSelectValue(vo.getEnabledmark(), "启用", "禁用"));

        vo.setQuestion(vo.getQuestion());

        vo.setAnswer(vo.getAnswer());

        vo.setCreatoruserid(generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));

        vo.setCreatortime(vo.getCreatortime());

        vo.setLastmodifyuserid(generaterSwapUtil.userSelectValue(vo.getLastmodifyuserid()));

        vo.setLastmodifytime(vo.getLastmodifytime());


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param lineQuestionForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid LineQuestionForm lineQuestionForm) throws DataException {
        String b = lineQuestionService.checkForm(lineQuestionForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        UserInfo userInfo = userProvider.get();
        LineQuestionEntity entity = lineQuestionService.getInfo(id);
        if (entity != null) {
            lineQuestionForm.setLastmodifyuserid(userInfo.getUserId());
            lineQuestionForm.setLastmodifytime(DateUtil.getNow());
            LineQuestionEntity subentity = JsonUtil.getJsonToBean(lineQuestionForm, LineQuestionEntity.class);
            subentity.setCreatoruserid(entity.getCreatoruserid());
            subentity.setCreatortime(entity.getCreatortime());
            boolean b1 = lineQuestionService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            QueryWrapper<LineQuestionOptionsEntity> LineQuestionOptionsqueryWrapper = new QueryWrapper<>();
            LineQuestionOptionsqueryWrapper.lambda().eq(LineQuestionOptionsEntity::getQuestionid, entity.getId());
            lineQuestionOptionsService.remove(LineQuestionOptionsqueryWrapper);
            if (lineQuestionForm.getLinequestionoptionsList() != null) {
                List<LineQuestionOptionsEntity> LineQuestionOptionsList = JsonUtil.getJsonToList(lineQuestionForm.getLinequestionoptionsList(), LineQuestionOptionsEntity.class);
                for (LineQuestionOptionsEntity entitys : LineQuestionOptionsList) {


                    entitys.setId(RandomUtil.uuId());
                    entitys.setQuestionid(entity.getId());
                    lineQuestionOptionsService.save(entitys);
                }
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        LineQuestionEntity entity = lineQuestionService.getInfo(id);
        if (entity != null) {
            lineQuestionService.delete(entity);
            QueryWrapper<LineQuestionOptionsEntity> queryWrapperLineQuestionOptions = new QueryWrapper<>();
            queryWrapperLineQuestionOptions.lambda().eq(LineQuestionOptionsEntity::getQuestionid, entity.getId());

            lineQuestionOptionsService.remove(queryWrapperLineQuestionOptions);
        }
        return ActionResult.success("删除成功");
    }


}
